#include <QDebug>
#include <QSqlQuery>
#include <QFileDialog>
#include <QMessageBox>
#include <qmath.h>
#include <QDesktopServices>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("nutrition_db.sqlite");

    m_statusLabel = new QLabel(ui->statusBar);
    ui->statusBar->addWidget(m_statusLabel);

    if (!db.open()) {
        m_statusLabel->setText(tr("Adatbázis megnyitása sikertelen"));
    } else {
        m_statusLabel->setText(tr("Adatbázis sikeresen megnyitva"));
    }

    m_query = new QSqlQuery(db);

    m_mealManageDialog = new DialogMealDataManage(&db, this);
    m_addFoodDialog = new DialogAddFood(m_mealManageDialog, &db, this);
    connect(m_addFoodDialog, SIGNAL(mealAdded()), this, SLOT(recalculateDisplay()));

    reader = new MealDataReader(m_query, &db, this);

    //reader->readFile("/home/mm/Asztal/kcalData.txt");
    breakFastModel = new MealModel(MealModel::MealType_BreakFast, ui->calendarWidget->selectedDate(), &db, this);
    lunchModel = new MealModel(MealModel::MealType_Lunch, ui->calendarWidget->selectedDate(), &db, this);
    dinnerModel = new MealModel(MealModel::MealType_Dinner, ui->calendarWidget->selectedDate(), &db, this);


    ui->tableViewBreakfast->setModel(breakFastModel);
    ui->tableViewDinner->setModel(dinnerModel);
    ui->tableViewLunch->setModel(lunchModel);

    ui->tableViewBreakfast->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewBreakfast->setSelectionMode(QAbstractItemView::SingleSelection);

    ui->tableViewLunch->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewLunch->setSelectionMode(QAbstractItemView::SingleSelection);

    ui->tableViewDinner->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewDinner->setSelectionMode(QAbstractItemView::SingleSelection);

    recalculateDisplay();
    m_report = new WebkitReport("../report/week_report.html", this);
    m_reportView = new DialogWebKitReportView(m_report, this);

    dietarySettings = new DialogSettings(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::recalculateDisplay()
{
    QDate currentDate = ui->calendarWidget->selectedDate();
    QDate periodFirstDay;
    QDate periodLastDay;

    QDate periodAnchorDate;
    int periodLength = 0;
    settings.beginGroup("timePeriod");
    periodLength = settings.value("length", 10).toInt();
    periodAnchorDate = settings.value("startDate").toDate();
    settings.endGroup();

    int daysFromPeriodStartDate = periodAnchorDate.daysTo(currentDate);
    int periodCnt = daysFromPeriodStartDate/periodLength;

    int currentPeriodDay = daysFromPeriodStartDate-periodCnt*periodLength;
    periodFirstDay = currentDate.addDays(-currentPeriodDay);
    periodLastDay = currentDate.addDays(periodLength - currentPeriodDay -1);

    ui->groupBoxPeriodData->setTitle(tr("Időkeret adatok: (%1 - %2)")
                                     .arg(periodFirstDay.toString("yyyy-MM-dd"))
                                     .arg(periodLastDay.toString("yyyy-MM-dd")));


    QSqlQuery *query = new QSqlQuery(db);
    QString queryStr;

    breakFastModel->setDate(currentDate);
    lunchModel->setDate(currentDate);
    dinnerModel->setDate(currentDate);

    ui->tableViewLunch->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableViewLunch->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
    ui->tableViewLunch->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);

    ui->tableViewDinner->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableViewDinner->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
    ui->tableViewDinner->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);

    ui->tableViewBreakfast->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableViewBreakfast->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
    ui->tableViewBreakfast->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);


    // periódus összes
    queryStr =  QString("SELECT "
                        "SUM(f.foodCalorie * m.foodAmount), " \
                        "SUM(f.foodFat * m.foodAmount), " \
                        "SUM(f.foodProtein * m.foodAmount), " \
                        "SUM(f.foodCh * m.foodAmount), " \
                        "SUM(f.foodCost * m.foodAmount) " \
                        "FROM foods f, meals m " \
            "WHERE m.mealDate BETWEEN \"%1\" AND \"%2\" AND f.rowid = m.foodId")
            .arg(periodFirstDay.toString("yyyy-MM-dd")).arg(periodLastDay.toString("yyyy-MM-dd"));
    if (query->exec(queryStr)) {
        if (query->next()) {
            setPeriodSumData(query->value(0).toDouble(),
                                query->value(1).toDouble(),
                                query->value(2).toDouble(),
                                query->value(3).toDouble(),
                                query->value(4).toDouble());
        } else {
            setPeriodSumData();
        }
    } else {
        qWarning() << query->lastError().databaseText();
    }

    /*// heti regggeli átlag
    queryStr =  QString("SELECT SUM(f.foodCalorie * m.foodAmount) FROM foods f, meals m "
            "WHERE m.mealDate BETWEEN \"%1\" AND \"%2\" AND f.rowid = m.foodId AND m.mealType = 0")
            .arg(firstWeekDay.toString("yyyy-MM-dd")).arg(lastWeekDay.toString("yyyy-MM-dd"));
    if (query->exec(queryStr)) {
        if (query->next()) {
            ui->labelDailyAvgBreakFast->setText(QString("%1 kCal").arg(query->value(0).toDouble()/7));
        } else {
            ui->labelDailyAvgBreakFast->setText("0 kCal");
        }
    } else {
        qWarning() << query->lastError().databaseText();
    }

    // heti ebéd átlag
    queryStr =  QString("SELECT SUM(f.foodCalorie * m.foodAmount) FROM foods f, meals m "
            "WHERE m.mealDate BETWEEN \"%1\" AND \"%2\" AND f.rowid = m.foodId AND m.mealType = 1")
            .arg(firstWeekDay.toString("yyyy-MM-dd")).arg(lastWeekDay.toString("yyyy-MM-dd"));
    if (query->exec(queryStr)) {
        if (query->next()) {
            ui->labelDailyAvgLunch->setText(QString("%1 kCal").arg(query->value(0).toDouble()/7));
        } else {
            ui->labelDailyAvgLunch->setText("0 kCal");
        }
    } else {
        qWarning() << query->lastError().databaseText();
    }

    // heti vacsora átlag
    queryStr =  QString("SELECT SUM(f.foodCalorie * m.foodAmount) FROM foods f, meals m "
            "WHERE m.mealDate BETWEEN \"%1\" AND \"%2\" AND f.rowid = m.foodId AND m.mealType = 2")
            .arg(firstWeekDay.toString("yyyy-MM-dd")).arg(lastWeekDay.toString("yyyy-MM-dd"));
    if (query->exec(queryStr)) {
        if (query->next()) {
            ui->labelDailyAvgDinner->setText(QString("%1 kCal").arg(query->value(0).toDouble()/7));
        } else {
            ui->labelDailyAvgDinner->setText("0 kCal");
        }
    } else {
        qWarning() << query->lastError().databaseText();
    }
    */

    //double cal, double fat, double protein, double ch, double cost

    // napi összes
    queryStr =  QString("SELECT "
                        "SUM(f.foodCalorie * m.foodAmount), " \
                        "SUM(f.foodFat * m.foodAmount), " \
                        "SUM(f.foodProtein * m.foodAmount), " \
                        "SUM(f.foodCh * m.foodAmount), " \
                        "SUM(f.foodCost * m.foodAmount) " \
                        "FROM foods f, meals m " \
                        "WHERE m.mealDate = \"%1\" AND f.rowid = m.foodId")
            .arg(currentDate.toString("yyyy-MM-dd"));
    if (query->exec(queryStr)) {
        if (query->next()) {
            setDailySumData(query->value(0).toDouble(),
                                query->value(1).toDouble(),
                                query->value(2).toDouble(),
                                query->value(3).toDouble(),
                                query->value(4).toDouble());
        } else {
            setDailySumData();
        }
    } else {
        qWarning() << query->lastError().databaseText();
    }

    // napi szummák
    for (int i = 0; i<3; i++) {
        queryStr =  QString("SELECT " \
                            "SUM(f.foodCalorie * m.foodAmount), " \
                            "SUM(f.foodFat * m.foodAmount), " \
                            "SUM(f.foodProtein * m.foodAmount), " \
                            "SUM(f.foodCh * m.foodAmount), " \
                            "SUM(f.foodCost * m.foodAmount) " \
                            "FROM foods f, meals m "
                "WHERE m.mealDate = \"%1\" AND f.rowid = m.foodId AND m.mealType = %2")
                .arg(currentDate.toString("yyyy-MM-dd"))
                .arg(i);
        if (query->exec(queryStr)) {
            if (query->next()) {
                setDailyMealSumData((MealModel::MealType)i,
                               query->value(0).toDouble(),
                               query->value(1).toDouble(),
                               query->value(2).toDouble(),
                               query->value(3).toDouble(),
                               query->value(4).toDouble());
            } else {
                setDailyMealSumData((MealModel::MealType)i);
            }
        } else {
            qWarning() << "SQL error:" << query->lastError().databaseText() << "IN query:" << queryStr;
        }
    }
}


void MainWindow::on_calendarWidget_clicked(const QDate &)
{
    recalculateDisplay();
}

void MainWindow::on_pushButtonAddBreakFast_clicked()
{
    m_addFoodDialog->setDate(ui->calendarWidget->selectedDate());
    m_addFoodDialog->setType(MealModel::MealType_BreakFast);
    m_addFoodDialog->show();
}

void MainWindow::on_pushButtonRemoveBreakFast_clicked()
{
    if (ui->tableViewBreakfast->selectionModel()->selectedRows(0).size()) {
        QSqlQuery *query = new QSqlQuery(db);
        int rowid = breakFastModel->data(ui->tableViewBreakfast->selectionModel()->selectedRows(0).first()).toInt();
        qWarning() << rowid << " del";
        QString deleteQuery = QString("DELETE FROM meals WHERE rowid = %1").arg(rowid);
        if (!query->exec(deleteQuery)) {
            qWarning() << query->lastError().databaseText();
        } else {
            recalculateDisplay();
        }
    }
}

void MainWindow::on_pushButtonAddLunch_clicked()
{
    m_addFoodDialog->setDate(ui->calendarWidget->selectedDate());
    m_addFoodDialog->setType(MealModel::MealType_Lunch);
    m_addFoodDialog->show();
}

void MainWindow::on_pushButtonRemoveLunch_clicked()
{
    if (ui->tableViewLunch->selectionModel()->selectedRows(0).size()) {
        QSqlQuery *query = new QSqlQuery(db);
        int rowid = lunchModel->data(ui->tableViewLunch->selectionModel()->selectedRows(0).first()).toInt();
        QString deleteQuery = QString("DELETE FROM meals WHERE rowid = %1").arg(rowid);
        if (!query->exec(deleteQuery)) {
            qWarning() << query->lastError().databaseText();
        } else {
            recalculateDisplay();
        }
    }
}

void MainWindow::on_pushButtoAddDinner_clicked()
{
    m_addFoodDialog->setDate(ui->calendarWidget->selectedDate());
    m_addFoodDialog->setType(MealModel::MealType_Dinner);
    m_addFoodDialog->show();
}

void MainWindow::on_pushButtonRemoveDinner_clicked()
{
    if (ui->tableViewDinner->selectionModel()->selectedRows(0).size()) {
        QSqlQuery *query = new QSqlQuery(db);
        int rowid = dinnerModel->data(ui->tableViewDinner->selectionModel()->selectedRows(0).first()).toInt();
        QString deleteQuery = QString("DELETE FROM meals WHERE rowid = %1").arg(rowid);
        if (!query->exec(deleteQuery)) {
            qWarning() << query->lastError().databaseText();
        } else {
            recalculateDisplay();
        }
    }
}

void MainWindow::on_actionQuit_triggered()
{
}

void MainWindow::on_actionImport_triggered()
{
   QString fn = QFileDialog::getOpenFileName(this, tr("Válaszd ki az adatfájlt fájlt"), QDir::homePath(), "*.*");
   if (!fn.isNull()) {
       QMessageBox msgBox;
       msgBox.setText("Törlöd a meglévő adatokat?");
       msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
       msgBox.setDefaultButton(QMessageBox::Yes);
       reader->readFile(fn, (msgBox.exec() == QMessageBox::Yes));
   }
}

void MainWindow::on_actionManageMealData_triggered()
{
    m_mealManageDialog->showMaximized();
}

void MainWindow::on_actionAboutQt_triggered()
{
    QApplication::aboutQt();
}

void MainWindow::on_actionWeboldal_triggered()
{
    QDesktopServices::openUrl(QUrl("http://code.google.com/p/nutrition-calculator"));
}

void MainWindow::on_actionDietarySettings_triggered()
{
    dietarySettings->show();
}

void MainWindow::on_actionWeeklyReport_triggered()
{
    QSqlQuery *query = new QSqlQuery(db);

    QStringList dayList;
    dayList << "het" << "ked" << "sze" << "csu" << "pen" << "szo" << "vas";

    QStringList mealTypeList;
    mealTypeList << "break" << "lunch" << "dinner";

    QString mealNames[3][7];
    float mealCalorie[3][7];
    float mealProtein[3][7];
    float mealCh[3][7];
    float mealFat[3][7];
    float mealCost[3][7];

    float mealCalorieSum[3];
    float mealProteinSum[3];
    float mealChSum[3];
    float mealFatSum[3];
    float mealCostSum[3];

    float mealCalorieCnt[3];
    float mealProteinCnt[3];
    float mealChCnt[3];
    float mealFatCnt[3];
    float mealCostCnt[3];

    for (int i = 0; i<3; i++) {
        for (int j = 0; j<7; j++) {
            mealCalorie[i][j] = 0;
            mealProtein[i][j] = 0;
            mealCh[i][j]      = 0;
            mealFat[i][j]     = 0;
            mealCost[i][j]     = 0;
        }

        mealCalorieSum[i] = 0;
        mealProteinSum[i] = 0;
        mealChSum[i]      = 0;
        mealFatSum[i]     = 0;
        mealCostSum[i]     = 0;

        mealCalorieCnt[i] = 0;
        mealProteinCnt[i] = 0;
        mealChCnt[i]      = 0;
        mealFatCnt[i]     = 0;
        mealCostCnt[i]     = 0;
    }

    QDate firstWeekDay = ui->calendarWidget->selectedDate().addDays(-ui->calendarWidget->selectedDate().dayOfWeek()+1);
    QDate lastWeekDay = ui->calendarWidget->selectedDate().addDays(7-ui->calendarWidget->selectedDate().dayOfWeek());

    int year;
    QString weekString = QString("%1. hét").arg(firstWeekDay.weekNumber(&year));
    if (year != lastWeekDay.year()) {
        weekString = QString("%1/%2. hét").arg(firstWeekDay.weekNumber(), lastWeekDay.weekNumber());
    }

    QString intervalString = QString("%1 - %2 %3")
                .arg(firstWeekDay.toString("yyyy MMM. d"))
                .arg(lastWeekDay.toString("yyyy MMM. d"))
                .arg(weekString);
    m_report->setField("titlediv_interval", intervalString);

    QString queryString = QString("SELECT m.mealDate, m.mealType, f.foodName, f.foodCalorie, f.foodProtein, f.foodCh, f.foodFat, f.foodCost, m.foodAmount "
            "FROM meals m, foods f WHERE m.foodId = f.rowid AND m.mealDate BETWEEN '%1' AND '%2'")
            .arg(firstWeekDay.toString("yyyy-MM-dd")).arg(lastWeekDay.toString("yyyy-MM-dd"));

    if (query->exec(queryString)) {
        while (query->next()) {
            QDate date = QDate::fromString(query->value(0).toString(), "yyyy-MM-dd");
            int mealType = query->value(1).toInt();
            if (mealType > 2) {
                qWarning() << "Invalid mealtype" << mealType;
            } else {
                float amount = query->value(8).toFloat();
                mealNames[mealType][date.dayOfWeek()-1].append(query->value(2).toString()+"<br>");
                mealCalorie[mealType][date.dayOfWeek()-1] += query->value(3).toFloat()  * amount;
                mealProtein[mealType][date.dayOfWeek()-1] += query->value(4).toFloat()  * amount;
                mealCh[mealType][date.dayOfWeek()-1] += query->value(5).toFloat()  * amount;
                mealFat[mealType][date.dayOfWeek()-1] += query->value(6).toFloat()  * amount;
                mealCost[mealType][date.dayOfWeek()-1] += query->value(7).toFloat()  * amount;


                mealCalorieSum[mealType] += query->value(3).toFloat() * amount;
                mealProteinSum[mealType] += query->value(4).toFloat() * amount;
                mealChSum[mealType] += query->value(5).toFloat()  * amount;
                mealFatSum[mealType] += query->value(6).toFloat()  * amount;
                mealCostSum[mealType] += query->value(7).toFloat()  * amount;
            }
        }
    }

    for (int i = 0; i<3; i++) {
        for (int j = 0; j<7; j++) {
            if(mealCalorie[i][j] != 0) {
                mealCalorieCnt[i]++;
            }

            if(mealProtein[i][j] != 0) {
                mealProteinCnt[i]++;
            }

            if(mealFat[i][j] != 0) {
                mealFatCnt[i]++;
            }

            if(mealCh[i][j] != 0) {
                mealChCnt[i]++;
            }

            if(mealCost[i][j] != 0) {
                mealCostCnt[i]++;
            }
        }
    }

    for (int j = 0; j<7; j++) { // hétfő ked szerda péntek
        QString fieldName, val;

        float dailyMealCalorie = 0;
        float dailyMealProtein = 0;
        float dailyMealCh = 0;
        float dailyMealFat = 0;
        float dailyMealCost = 0;

        for (int i = 0; i<3; i++) { // reggeli ebéd vacsora
            fieldName = QString("%1_%2_name").arg(mealTypeList[i]).arg(dayList[j]);
            if (!mealNames[i][j].isEmpty()) {
                m_report->setField(fieldName, mealNames[i][j]);

                fieldName = QString("%1_energy_%2").arg(mealTypeList[i]).arg(dayList[j]);
                val = QString("%1 kCal").arg(mealCalorie[i][j]);
                dailyMealCalorie += mealCalorie[i][j];
                m_report->setField(fieldName, val);

                fieldName = QString("%1_prot_%2").arg(mealTypeList[i]).arg(dayList[j]);
                val = QString("%1 g").arg(mealProtein[i][j]);
                dailyMealProtein += mealProtein[i][j];
                m_report->setField(fieldName, val);

                fieldName = QString("%1_ch_%2").arg(mealTypeList[i]).arg(dayList[j]);
                val = QString("%1 g").arg(mealCh[i][j]);
                dailyMealCh += mealCh[i][j];
                m_report->setField(fieldName, val);

                fieldName = QString("%1_fat_%2").arg(mealTypeList[i]).arg(dayList[j]);
                val = QString("%1 g").arg(mealFat[i][j]);
                dailyMealFat += mealFat[i][j];
                m_report->setField(fieldName, val);

                fieldName = QString("%1_cost_%2").arg(mealTypeList[i]).arg(dayList[j]);
                val = QString("%1 Ft").arg(mealCost[i][j]);
                dailyMealCost += mealCost[i][j];
                m_report->setField(fieldName, val);
            }
        }

        // napi összegek kiírása
        fieldName = QString("daily_%1_cost").arg(dayList[j]);

        val = QString("%1 Ft").arg(dailyMealCost);
        m_report->setField(fieldName, val);

        fieldName = QString("daily_prot_%1").arg(dayList[j]);
        val = QString("%1 g").arg(dailyMealProtein);
        m_report->setField(fieldName, val);

        fieldName = QString("daily_fat_%1").arg(dayList[j]);
        val = QString("%1 g").arg(dailyMealFat);
        m_report->setField(fieldName, val);

        fieldName = QString("daily_ch_%1").arg(dayList[j]);
        val = QString("%1 g").arg(dailyMealCh);
        m_report->setField(fieldName, val);

        fieldName = QString("daily_energy_%1").arg(dayList[j]);
        val = QString("%1 g").arg(dailyMealCalorie);
        m_report->setField(fieldName, val);


        // összegek kiírása
        /*fieldName = QString("%1_sum_calorie").arg(mealTypeList[i]);
        val = QString("%1 kCal").arg(mealCalorieSum[i]);
        m_report->setField(fieldName, val);

        fieldName = QString("%1_sum_protein").arg(mealTypeList[i]);
        val = QString("%1 g").arg(mealProteinSum[i]);
        m_report->setField(fieldName, val);

        fieldName = QString("%1_sum_ch").arg(mealTypeList[i]);
        val = QString("%1 g").arg(mealChSum[i]);
        m_report->setField(fieldName, val);

        fieldName = QString("%1_sum_fat").arg(mealTypeList[i]);
        val = QString("%1 g").arg(mealFatSum[i]);
        m_report->setField(fieldName, val);

        fieldName = QString("%1_sum_cost").arg(mealTypeList[i]);
        val = QString("%1 Ft").arg(mealCostSum[i]);
        m_report->setField(fieldName, val);*/

        // átlagok kiírása
        /*if (mealCalorieCnt[i]) {
            fieldName = QString("%1_avg_calorie").arg(mealTypeList[i]);
            val = QString("%1 kCal").arg(QString::number(mealCalorieSum[i]/mealCalorieCnt[i], 'f', 2));
            m_report->setField(fieldName, val);
        }

        if (mealProteinCnt[i]) {
            fieldName = QString("%1_avg_protein").arg(mealTypeList[i]);
            val = QString("%1 g").arg(QString::number(mealProteinSum[i]/mealProteinCnt[i], 'f', 2));
            m_report->setField(fieldName, val);
        }

        if (mealChCnt[i]) {
            fieldName = QString("%1_avg_ch").arg(mealTypeList[i]);
            val = QString("%1 g").arg(QString::number(mealChSum[i]/mealChCnt[i], 'f', 2));
            m_report->setField(fieldName, val);
        }

        if (mealFatCnt[i]) {
            fieldName = QString("%1_avg_fat").arg(mealTypeList[i]);
            val = QString("%1 g").arg(QString::number(mealFatSum[i]/mealFatCnt[i], 'f', 2));
            m_report->setField(fieldName, val);
        }

        if (mealCostCnt[i]) {
            fieldName = QString("%1_avg_cost").arg(mealTypeList[i]);
            val = QString("%1 Ft").arg(QString::number(mealCostSum[i]/mealCostCnt[i], 'f', 2));
            m_report->setField(fieldName, val);
        }*/
    }

    m_reportView->showMaximized();
    m_reportView->reloadPage();

    m_reportView->show();
}

void MainWindow::on_actionPrintMenuCard_triggered()
{

}

void MainWindow::on_actionTimePeriod_triggered()
{
    timePeriodSettings.show();
}

void MainWindow::setDailyMealSumData(MealModel::MealType meal, double cal, double fat, double protein, double ch, double cost)
{
    QString mealName;
    switch (meal) {
    case MealModel::MealType_BreakFast:
        mealName = "Breakfast";
        break;
    case MealModel::MealType_Lunch:
        mealName = "Lunch";
        break;
    case MealModel::MealType_Dinner:
        mealName = "Dinner";
        break;
    }

    QStringList dataTypeList;
    dataTypeList << "Energy" << "Fat" << "Protein" << "Ch" << "Cost";
    QStringList suffixList;
    suffixList <<  "kCal" << "g" << "g" << "g" << "Ft";
    for (int i = 0; i< dataTypeList.size(); i++) {
        QString labelName = "labelToday"+mealName+dataTypeList[i]+"Sum";
        double value;
        switch (i) {
        case 0: value = cal; break;
        case 1: value = fat; break;
        case 2: value = protein; break;
        case 3: value = ch; break;
        case 4: value = cost; break;
        }
        setLabelValue(labelName, value, suffixList[i]);
    }
}


void MainWindow::setDailySumData(double cal, double fat, double protein, double ch, double cost)
{
    QStringList dataTypeList;
    dataTypeList << "Energy" << "Fat" << "Protein" << "Ch" << "Cost";
    QStringList suffixList;
    suffixList <<  "kCal" << "g" << "g" << "g" << "Ft";
    for (int i = 0; i< dataTypeList.size(); i++) {
        QString labelName = "labelToday"+dataTypeList[i]+"Sum";
        double value;
        switch (i) {
        case 0: value = cal; break;
        case 1: value = fat; break;
        case 2: value = protein; break;
        case 3: value = ch; break;
        case 4: value = cost; break;
        }
        setLabelValue(labelName, value, suffixList[i]);
    }
}


void MainWindow::setPeriodSumData(double cal, double fat, double protein, double ch, double cost)
{
    QStringList dataTypeList;
    dataTypeList << "Energy" << "Fat" << "Protein" << "Ch" << "Cost";
    QStringList suffixList;
    suffixList <<  "kCal" << "g" << "g" << "g" << "Ft";
    for (int i = 0; i< dataTypeList.size(); i++) {
        QString labelName = "labelPeriod"+dataTypeList[i]+"Sum";
        double value;
        switch (i) {
        case 0: value = cal; break;
        case 1: value = fat; break;
        case 2: value = protein; break;
        case 3: value = ch; break;
        case 4: value = cost; break;
        }
        setLabelValue(labelName, value, suffixList[i]);
    }
}

bool MainWindow::setLabelValue(QString labelName, double value, QString suffix)
{
    QLabel *label = ui->centralWidget->findChild<QLabel*>(labelName);
    if (label != 0) {
        label->setText(QString("%1 %2").arg(value).arg(suffix));
        return true;
    }
    return false;
}
